import { Controller, Get, Post, Body, Patch, Param, Delete, UseInterceptors, UploadedFile, Res } from '@nestjs/common';
import { UploadService } from './upload.service';
import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express'; // 单个文件, 多个文件
import { join } from 'path';
import type { Response } from 'express';
import { zip } from 'compressing';
import { ApiTags } from '@nestjs/swagger';

// 这里没有开启文档版本管理---/upload/album
@Controller('upload')
@ApiTags('上传接口') // swagger分组接口
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post('album')
  @UseInterceptors(FileInterceptor('file')) // 使用处理文件的中间件
  upload (@UploadedFile() file) {
    console.log(file);
    return true;
  }

  // download 直接下载
  @Get('export')
  downLoad(@Res() res: Response) {
    const url = join(__dirname,'../images/1679280640465.jpg');
    console.log(url);
    res.download(url);
  }

  // 使用文件流的方式下载
  @Get('stream')
  async down (@Res() res:Response) {
    const url = join(__dirname,'../images/1679280640465.jpg');
    const tarStream  = new zip.Stream();
    await tarStream.addEntry(url);
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader(
      'Content-Disposition',  
      `attachment; filename=testName`,
    );
    tarStream.pipe(res);
  }


  @Post()
  create(@Body() createUploadDto: CreateUploadDto) {
    return this.uploadService.create(createUploadDto);
  }

  @Get()
  findAll() {
    return this.uploadService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.uploadService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUploadDto: UpdateUploadDto) {
    return this.uploadService.update(+id, updateUploadDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.uploadService.remove(+id);
  }
}
